import { ref } from 'vue'
import type { TreeNode, User } from '../types'
import request from '/@/utils/request'

export const usePersonSelector = () => {
  // 状态变量
  const treeData = ref<TreeNode[]>([])
  const treeLoading = ref(false)
  const userList = ref<User[]>([])
  const tableLoading = ref(false)
  const total = ref(0)
  const currentDepartment = ref('')
  const currentDepartmentId = ref('')
  const isExternal = ref(false)
  const currentPage = ref(1)
  const pageSize = ref(10)
  const searchResults = ref<TreeNode[]>([])

  // 加载组织树数据
  const loadTreeData = async () => {
    treeLoading.value = true
    try {
      const data: any = await request({
        url: '/api/employees/departments/list',
        method: 'get',
      })
      console.log(data)
      if (data.code === 0) {
        // 添加外部人员节点
        // const externalNode = {
        //   id: 'external',
        //   label: '外部人员',
        //   isLeaf: true,
        //   isExternal: true,
        // }
        // treeData.value = [...res.data, externalNode]
        treeData.value = [...data.result.rows]
        return data.result.rows
      } else {
        return []
      }
    } catch (error) {
      console.error('加载部门失败', error)
      // 移除错误提示，因为即使获取失败也不影响基本使用
      return []
    } finally {
      treeLoading.value = false
    }
  }

  // 加载部门子节点
  const loadDepartmentChildren = async (parentId: string | null = null) => {
    treeLoading.value = true
    try {
      const response = await request({
        url: '/api/employees/departments/list',
        method: 'get',
        params: {
          page: 1,
          limit: 100,
          parentId,
        },
      })

      // 确保完全获取响应数据
      const data = response.data || response

      // 添加调试信息
      console.log('部门数据响应:', data)

      if (data.code === 0 && data.result && Array.isArray(data.result.rows)) {
        // 转换部门数据
        const nodes = data.result.rows.map((item: any) => ({
          id: item.id,
          label: item.name || item.shortName,
          isLeaf: false,
          hasChildren: true,
          children: [],
        }))

        // 确保处理完成
        console.log(`成功加载${nodes.length}个部门节点`)
        return nodes
      } else {
        console.warn('加载部门子节点失败:', data.msg || '返回数据结构不符合预期')
        return []
      }
    } catch (error) {
      console.error('加载部门子节点失败', error)
      return []
    } finally {
      treeLoading.value = false
    }
  }

  // 搜索部门
  const searchDepartments = async (keyword: string) => {
    if (!keyword.trim()) {
      searchResults.value = []
      return []
    }

    treeLoading.value = true
    try {
      const response = await request({
        url: '/api/employees/departments/search',
        method: 'get',
        params: {
          page: 1,
          limit: 100,
          name: keyword,
        },
      })

      const data = response.data || response

      if (data.code === 0 && data.result && data.result.rows) {
        // 转换搜索结果数据
        const results = data.result.rows.map((item: any) => ({
          id: item.id,
          label: item.name || item.shortName,
          isLeaf: true, // 搜索结果默认为叶子节点
          parentId: item.parentId,
        }))

        searchResults.value = results
        return results
      } else {
        console.warn('搜索部门失败:', data.msg)
        searchResults.value = []
        return []
      }
    } catch (error) {
      console.error('搜索部门失败', error)
      searchResults.value = []
      return []
    } finally {
      treeLoading.value = false
    }
  }

  // 加载用户列表数据
  const loadUserList = async (params: { deptId?: string; isExternal?: boolean; keyword?: string; page?: number; pageSize?: number }) => {
    const { deptId, keyword, page = 1, pageSize: size = 10 } = params
    // const isExternalFlag = params.isExternal ? 2 : 1 // 平台归属1:红有，2:本系统
    const isExternalFlag = 1 // 只使用内部人员，固定平台归属为1:红有

    tableLoading.value = true
    try {
      currentPage.value = page
      pageSize.value = size

      const response = await request({
        url: '/api/user',
        method: 'get',
        params: {
          page,
          limit: size,
          name: keyword || '',
          mobile: '',
          deptId: deptId || '',
          isExternal: isExternalFlag,
        },
      })

      // 正确处理响应数据
      const data = response.data || response

      if (data.code === 0 && data.result) {
        total.value = data.result.count || 0
        // 映射API返回的用户数据到组件内部格式
        userList.value = (data.result.rows || []).map((item: any) => ({
          id: item.id || item.userId,
          name: item.name || item.userName || '未命名用户',
          avatar: item.avatar,
          mobile: item.mobile || '-',
          email: item.email || '-',
          position: item.position || '-',
          departmentName: item.departmentName || '',
          isExternal: false, // 全部设为内部人员
        }))
        return {
          total: total.value,
          data: userList.value,
        }
      } else {
        console.error('加载用户列表失败:', data)
        return {
          total: 0,
          data: [],
        }
      }
    } catch (error) {
      console.error('加载用户列表失败', error)
      return {
        total: 0,
        data: [],
      }
    } finally {
      tableLoading.value = false
    }
  }

  // 切换部门
  const selectDepartment = (dept: TreeNode | null) => {
    if (!dept) {
      currentDepartment.value = ''
      currentDepartmentId.value = ''
      isExternal.value = false
      return
    }

    // 移除外部人员逻辑
    // if (dept.isExternal) {
    //   currentDepartment.value = '外部人员'
    //   currentDepartmentId.value = ''
    //   isExternal.value = true
    // } else {
    currentDepartment.value = dept.label || ''
    currentDepartmentId.value = dept.id || ''
    isExternal.value = false
    // }
  }

  return {
    treeData,
    treeLoading,
    userList,
    tableLoading,
    total,
    currentDepartment,
    currentDepartmentId,
    isExternal,
    currentPage,
    pageSize,
    searchResults,
    loadTreeData,
    loadDepartmentChildren,
    searchDepartments,
    loadUserList,
    selectDepartment,
  }
}
